//
//  LFStatusVM.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/3/25.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit

import SDWebImage

class LFStatusVM: NSObject {
    
      //MARK: -- 单例
   static let sharedInstance = LFStatusVM()
    
   private override init() {
        super.init()
    }

      //MARK: -- 网络请求home界面数据
    func loadHomeData(since_id:Int64, max_id:Int64, completion:(success:[LFStatus]?,error:NSError?) ->()) {
        
        
        let URLString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var parameters : [String: AnyObject] = [
            "access_token" : LFGlobalUserAccountsViewModel.sharedUserAccounts.userAccounts!.access_token!
        ]
        
        //则需要拉下刷新
        if  since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
            //则需要上啦刷新
        }else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id - 1)
        }
      
        LFHTTPManager.sharedManager.GETData(URLString, parameters: parameters) { (result, error) -> () in
            
            
            //判断数据是否成功
            if error != nil {
              completion(success: nil, error: error)
                return
            }
//              字典转换类型
            if let statusArr = result?["statuses"] as? [[String : AnyObject]] {
                
                var mutiStatus = [LFStatus]()
                
                for dict in statusArr {
                    
                    let status = LFStatus(dict: dict)
                    
                    mutiStatus.append(status)
                }
                
                self.cacheWebImage(mutiStatus, completion: completion)
//                completion(success: mutiStatus, error: nil)
            }
        }
    }
    
      //MARK: -- 缓存微博照片 获取服务器照片的大小
    private func cacheWebImage(mutiStatus:[LFStatus],completion:(success:[LFStatus]?,error:NSError?) ->()) {
        
        let group = dispatch_group_create()
        
        var length: CGFloat = 0
        
        //查找图片下载
        for status in mutiStatus {
            
            var downURLs = status.thumbnailPicURLs
            
            //等于nil 原生View没有配图 找转发的
            if downURLs == nil {
                downURLs = status.retweeted_status?.thumbnailPicURLs
            }
            //转发的配图也没有
            if downURLs == nil {
                //继续
                continue
            }
            
            //能到这里 ，说明有图片下载，处理只有一张的图片就可以了，多张图在界面里面下载，要不然会卡死在登录界面
            if downURLs?.count == 1 {
               let downUrl = downURLs![0]
                //进入组
                dispatch_group_enter(group)
                //使用SD下载
                SDWebImageManager.sharedManager().downloadImageWithURL(downUrl, options: SDWebImageOptions(rawValue: 0), progress: nil , completed: { (resultImage, error, _, _, _) -> Void in
                    //离开组
                    dispatch_group_leave(group)
                    //判断错误
                    if error != nil {
                        print("下载一张图片错误")
                        return
                    }
                    //没有错继续
                    //计算大小
                    let data = UIImagePNGRepresentation(resultImage)
                    length += CGFloat(data!.length)
                })
            }
        }
        
        //查找完，在通知我加载
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            //计算图片大小
            let len = length / 1024.0 / 1024.0
            //保留2位数
            let l = String(format: "%.2f", arguments: [len])
            print("所有图片都缓存完成: \(l) MB")
            
            //完成回调
            completion(success: mutiStatus, error: nil)
        }
        
        
    }
    
}
